package tom.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.event.dom.client.KeyDownEvent;

public class OverwriteLevel extends Composite {

	private static DialogBox dlg;

	private static OverwriteLevel owr;

	private static OverwriteLevelUiBinder uiBinder = GWT
			.create(OverwriteLevelUiBinder.class);

	private DialogExec exec;
	
	private String pgmId;

	@UiField
	Button btnOK;
	@UiField
	PasswordTextBox password;
	@UiField
	TextBox user;
	@UiField
	Button btnCancel;

	private ServiceAsync myService = Library.getService();

	private AsyncCallback<Integer> loginCallback = new AsyncCallback<Integer>() {
		public void onFailure(Throwable caught) {
			Window.alert(caught.getMessage());
		}

		public void onSuccess(Integer obj) {
			// Window.alert(obj.toString());
			dlg.hide();
			exec.execute(obj);
		}
	};

	interface OverwriteLevelUiBinder extends UiBinder<Widget, OverwriteLevel> {
	}

	public OverwriteLevel() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	public static void show(DialogExec exec, String pgmId) {
		// LookupDialog.output = output;
		if (dlg == null) {
			owr = new OverwriteLevel();
			dlg = GWT.create(DialogBox.class);
			dlg.setTitle("ตรวจสิทธิผู้ใช้พิเศษ");
			dlg.setWidget(owr);
			dlg.setModal(true);
		}
		owr.pgmId = pgmId;
		owr.exec = exec;
		owr.user.setText(null);
		owr.password.setText(null);
		dlg.center();
		owr.user.setFocus(true);
	}

	@UiHandler("btnOK")
	void onBtnOKClick(ClickEvent event) {
		myService.verify(pgmId, user.getText(), password.getValue(), loginCallback);
	}

	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
		dlg.hide();
	}

	@UiHandler("user")
	void onUserKeyDown(KeyDownEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			password.setFocus(true);
		}
	}

	@UiHandler("password")
	void onPasswordKeyDown(KeyDownEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			onBtnOKClick(null);
		}
	}
}
